package com.tdam2013.grupo07.fragments;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;

import android.app.ListFragment;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.Context;
import android.content.Loader;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.tdam2013.grupo07.R;
import com.tdam2013.grupo07.data.DatabaseHelper;
import com.tdam2013.grupo07.data.DatabaseHelperSingleton;
import com.tdam2013.grupo07.loader.ConectividadCursorLoader;

public class FragmentTabHistorialConectividad extends ListFragment implements LoaderCallbacks<Cursor>
{
	private ConectividadAdapter conectividadAdapter;
	private final int CONECTIVIDAD_LOADER_ID=0;
	
	@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
	{
            return inflater.inflate(R.layout.fragmenttab_historial, container,
                            false);
    }
	
	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
	    super.onViewCreated(view, savedInstanceState);
	    registerForContextMenu(getListView());
	}

    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
    	super.onCreate(savedInstanceState);
        conectividadAdapter=new ConectividadAdapter(getActivity(), null);
		getLoaderManager().initLoader(CONECTIVIDAD_LOADER_ID, null, this);
        setListAdapter(conectividadAdapter);
    }
    
    @Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo)
	{
		super.onCreateContextMenu(menu, v, menuInfo);
		menu.setHeaderTitle(getResources().getString(R.string.historial_menu_contextual_mensajes_titulo));
		menu.add(0, v.getId(), 0, getResources().getString(R.string.historial_menu_contextual_accion_eliminar));
	}
    
    @Override
	public boolean onContextItemSelected(MenuItem item)
	{
		if (item.getTitle() == getResources().getString(R.string.historial_menu_contextual_accion_eliminar))
		{
			AdapterContextMenuInfo menuInfoAdapter = (AdapterContextMenuInfo) item.getMenuInfo();
			DatabaseHelperSingleton.getInstance(getActivity()).getDatabaseHelper().eliminarRegistroConectividad(menuInfoAdapter.id);
			refresh();
			Toast.makeText(getActivity(),getResources().getString(R.string.historial_registro_eliminado), Toast.LENGTH_SHORT).show();
			return true;
		}
		return false;
	}
    
    public void refresh()
    {
    	getLoaderManager().restartLoader(CONECTIVIDAD_LOADER_ID,null, this);
    }
    
    public class ConectividadAdapter extends CursorAdapter {
		private LayoutInflater inflater;
		
		class ItemContenedor {
			ImageView itemIcono;
			TextView itemAccionPrincipal;
			TextView itemFechaAccion;
		}
		
		public ConectividadAdapter(Context context, Cursor cursor) {
			super(context, cursor, false);
			inflater=LayoutInflater.from(context);
		}

		@Override
		public View newView(Context context, Cursor cursor, ViewGroup parent) {
			View view = inflater.inflate(R.layout.item_historial_conectividad, null);
			ItemContenedor itemContenedor = new ItemContenedor();
			itemContenedor.itemIcono = (ImageView) view.findViewById(R.id.iconoAccion);
			itemContenedor.itemAccionPrincipal = (TextView) view.findViewById(R.id.accionPrincipal);
			itemContenedor.itemFechaAccion =  (TextView) view.findViewById(R.id.fechaAccion);
			view.setTag(itemContenedor);

			view = this.updateView(view, cursor);
			
			return view;
		}
		
		@Override
		public void bindView(View view, Context context, Cursor cursor)
		{
			view = this.updateView(view, cursor);
		}
		
		public View updateView(View view, Cursor cursor) {
			
			if (view != null)
			{
				ItemContenedor itemContenedor;				
				itemContenedor = (ItemContenedor) view.getTag();
				
				int conectividadTipo=cursor.getInt(cursor.getColumnIndex(DatabaseHelper.colConectividadTipo));;
				int conectividadEstado=cursor.getInt(cursor.getColumnIndex(DatabaseHelper.colConectividadEstado));
				
				if(conectividadEstado==DatabaseHelper.CONECTIVITY_STATE_CONECTED)
				{
					if(conectividadTipo==DatabaseHelper.CONECTIVITY_TYPE_WIFI)
					{
						itemContenedor.itemAccionPrincipal.setText(R.string.historial_conectividad_wifi);
						itemContenedor.itemIcono.setImageResource(R.drawable.wifi_on);
					}
					else
					{
						itemContenedor.itemAccionPrincipal.setText(R.string.historial_conectividad_mobile_network);
						itemContenedor.itemIcono.setImageResource(R.drawable.datos_on);
					}
				}
				else
				{
					itemContenedor.itemAccionPrincipal.setText(R.string.historial_conectividad_none);
					itemContenedor.itemIcono.setImageResource(R.drawable.wifi_off);
				}
				Date date=new Date(cursor.getLong(cursor.getColumnIndex(DatabaseHelper.colConectividadFecha)));
				SimpleDateFormat formatter = new SimpleDateFormat(getResources().getString(R.string.date_time_format));
				itemContenedor.itemFechaAccion.setText(formatter.format(date));
			}
			return view;
		}
	}
    
    @Override
	public Loader<Cursor> onCreateLoader(int id, Bundle args) {
		SharedPreferences preferences= PreferenceManager.getDefaultSharedPreferences(getActivity());
		String logOrder=preferences.getString(getResources().getString(R.string.lista_ordenamiento_historial_cronologico), getResources().getString(R.string.ajustes_ordenamiento_opciones_desc));
		String selection="";
		LinkedList<String> selectionArgs=new LinkedList<String>();
		if(preferences.getBoolean(getResources().getString(R.string.activity_ajustes_filtrar_historial_conectividad_opcion_disconnect_key), true))
		{
			selection= String.format(" %s = ?", DatabaseHelper.colConectividadTipo);
			selectionArgs.add(String.valueOf(DatabaseHelper.CONECTIVITY_TYPE_DISCONNECT));
		}
		if(preferences.getBoolean(getResources().getString(R.string.activity_ajustes_filtrar_historial_conectividad_opcion_network_key), true))
		{
			selection+=selectionArgs.size()!=0?selection= String.format(" OR %s = ?", DatabaseHelper.colConectividadTipo): String.format(" %s = ?", DatabaseHelper.colConectividadTipo);
			selectionArgs.add(String.valueOf(DatabaseHelper.CONECTIVITY_TYPE_NETWORK));
		}
		if(preferences.getBoolean(getResources().getString(R.string.activity_ajustes_filtrar_historial_conectividad_opcion_wifi_key), true))
		{
			selection+=selectionArgs.size()!=0?selection= String.format(" OR %s = ?", DatabaseHelper.colConectividadTipo): String.format(" %s = ?", DatabaseHelper.colConectividadTipo);
			selectionArgs.add(String.valueOf(DatabaseHelper.CONECTIVITY_TYPE_WIFI));
		}
		return new ConectividadCursorLoader(getActivity(), selection, selectionArgs.toArray(new String[selectionArgs.size()]), String.format("%s %s",DatabaseHelper.colConectividadFecha, logOrder));
	}

	@Override
	public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
		conectividadAdapter.swapCursor(cursor);		
	}

	@Override
	public void onLoaderReset(Loader<Cursor> cursor) {
		conectividadAdapter.swapCursor(null);
	}
    
}
